<template>
  <div v-loading="loading">
    <div class="text-right mb-3" v-if="viewMode">
      <el-button @click="handlePrint">
        <i class="fa fa-fw fa-print"></i>
        打印
      </el-button>
      <el-button @click="handleExport" :loading="downloadLoading">
        <i class="fa fa-fw fa-download"></i>
        导出
      </el-button>
    </div>
    <div :id="printId">
      <table class="w-100">
        <tbody>
          <tr>
            <td colspan="5">
              <h3 class="text-center">{{ tableTitle }}</h3>
            </td>
          </tr>
          <tr>
            <td colspan="5" class="text-left">
              表&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;号：G4表
            </td>
          </tr>
          <tr>
            <td colspan="5" class="text-left">制表机关：中国银行保险监督管理委员会</td>
          </tr>
          <tr>
            <td colspan="5" class="text-left">数据单位：万元</td>
          </tr>
          <tr>
            <td colspan="3" width="50%" class="text-left">填报单位：{{ orgName }}</td>
            <td colspan="2" class="text-left">{{ dateLabel }}</td>
          </tr>
        </tbody>
      </table>

      <table class="table table-bordered text-center table-vertical-middle table-sm mb-0">
        <colgroup>
          <col width="39%" />
          <col width="5%" />
          <col width="18%" />
          <col width="19%" />
          <col width="19%" />
        </colgroup>
        <tbody>
          <tr class="bd-1">
            <td rowspan="3">项目</td>
            <td rowspan="3">代码</td>
            <td>A</td>
            <td>B</td>
            <td>C</td>
          </tr>
          <tr class="bd-1">
            <td colspan="3">本期累计数（发生额）</td>
          </tr>
          <tr class="bd-1">
            <td>
              国有控股
              <div>融资担保机构</div>
            </td>
            <td>
              民营及外资
              <div>融资担保机构</div>
            </td>
            <td>合计</td>
          </tr>
          <tr v-for="item in editData" class="bd-1" :key="item.b">
            <td class="text-left" :class="item.style">{{ item.a }}</td>
            <td>{{ item.b }}</td>
            <td :class="item.notedit ? '' : tdClass">
              <span v-if="viewMode || item.notedit">{{ item.c }}</span>
              <el-input
                v-else
                class="text-center"
                v-input-number="{ fixed: 0 }"
                @input="setNotEditNumber"
                v-model="item.c"
              ></el-input>
            </td>
            <td :class="item.notedit ? '' : tdClass">
              <span v-if="viewMode || item.notedit">{{ item.d }}</span>
              <el-input
                v-else
                class="text-center"
                v-input-number="{ fixed: 0 }"
                @input="setNotEditNumber"
                v-model="item.d"
              ></el-input>
            </td>
            <td>{{ add(item.c, item.d) || 0 }}</td>
          </tr>
        </tbody>
      </table>

      <table class="w-100">
        <tbody>
          <tr>
            <td class="text-left" width="30%">统计负责人：</td>
            <td colspan="2" width="40%">
              填表人及联系方式：{{ tableInfo.submit_person_name || user.realName }}
              {{ tableInfo.phone_number || user.phoneNumber }}
            </td>
            <td colspan="2" width="30%">报出日期：{{ createDate }}</td>
          </tr>
          <tr>
            <td colspan="5" rowspan="10" class="text-left">
              <div class="mt-3">
                <pre class="report-desc">{{ reportDesc }}</pre>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    <div class="mb-5 text-center" v-if="!viewMode">
      <el-button :loading="saveLoading" class="btn-long" type="primary" @click="save">
        保存
      </el-button>

      <el-button class="mr-2 btn-long" :loading="saveLoading" @click="beforeClose">取消</el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { add, sub, excelTableExport, domHasClass, printWithIframe } from '@vimi/utils-tool'
export default {
  components: {},
  props: {
    queryYear: {
      type: Number,
      required: true,
    },
    viewMode: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      tableData: [
        { a: '营业收入', b: '401', c: '', d: '', e: '', notedit: true },
        { a: '担保业务收入', b: '402', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '其中：融资担保费收入', b: '403', c: '', d: '', e: '', style: 'text-indent-2' },
        { a: '减：提取未到期责任准备金', b: '404', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '其他营业收入', b: '405', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '营业支出', b: '406', c: '', d: '', e: '', notedit: true },
        { a: '提取担保赔偿准备金', b: '407', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '税金及附加', b: '408', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '其他营业支出', b: '409', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '营业利润', b: '410', c: '', d: '', e: '', notedit: true },
        { a: '加：营业外收入', b: '411', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '减：营业外支出', b: '412', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '利润总额', b: '413', c: '', d: '', e: '', notedit: true },
        { a: '减：所得税费用', b: '414', c: '', d: '', e: '', style: 'text-indent-1' },
        { a: '净利润（净亏损则前加“－”号填列）', b: '415', c: '', d: '', e: '', notedit: true },
      ],
      reportDesc: `填报说明：
1.本表由各省、自治区、直辖市融资担保公司监督管理部门填报。
2.本表统计范围为在本省（区、市）持有融资担保业务经营许可证的融资担保法人机构，本省（区、市）融资担保法人机构在省（区、市）内外设立的分支机构数据需汇总至法人机构后统一填报。
3.本表依据《中华人民共和国会计法》、《企业财务会计报告条例》（国务院令第287号）、《企业会计准则》、《金融企业财务规则》（财政部令第42号）等有关规定填写。
4.外币数据须按报告期末最后一天国家外汇管理局公布的基准汇价折合为人民币数据进行汇总。
5.填列的金额按四舍五入保留整数。
6.本报表为年报，报送时间为年后1月底前。
7.校验关系：[A]+[B]=[C]，[401]-[406]=[410]，[410]+[411]-[412]=[413]，[413]-[414]=[415]，[402]-[404]+[405]=[401]，[407]+[408]+[409]=[406]。
`,
      downloadLoading: false,
      loading: false,
      tableName: 'report_year',
      tableTitle: 'XX省（区、市）融资担保公司利润情况',
      params: {
        'year_type.eq': 3,
        subKey: 'report_year_income_detail.report_year_id',
      },
      tableInfo: {},
      order: {},
      saveLoading: false,
      editData: [],
    }
  },
  computed: {
    ...mapGetters(['org', 'user']),
    orgName() {
      return this.org.orgName
    },
    dateLabel() {
      return `${this.queryYear}年`
    },
    printId() {
      return `g4-${this.queryYear}`
    },
    tdClass() {
      return this.viewMode ? '' : 'input-td'
    },
    createDate() {
      return this.$utils.dateFormat(this.tableInfo.update_time || new Date(), 'yyyy年MM月dd日')
    },
  },
  watch: {
    queryYear: {
      handler: function () {
        this.params['service_id.eq'] = this.clientId
        this.params['year_number.eq'] = this.queryYear
        this.getData()
      },
      immediate: true,
    },
  },
  created() {},
  mounted() {},
  methods: {
    add,
    getData() {
      this.loading = true
      this.$api
        .getData(this.$serviceName, this.tableName, this.params, this.order)
        .then(res => {
          this.tableInfo = res?.data?.[0] ?? {}
          const data = this.tableInfo.report_year_income_detail || []
          this.tableData = this.tableData.map(item => {
            const row = data.find(d => d.dimension_key === item.b) || {}
            item.c = +row.com_funds || ''
            item.d = +row.un_com_funds || ''
            item.id = row.id
            return item
          })
          this.editData = this.tableData.map(item => {
            return { ...item }
          })
        })
        .finally(() => {
          this.loading = false
        })
    },
    setNotEditNumber() {
      const sum401 = {
        c: sub(this.sumKey([402, 405]).c, this.sumKey([404]).c) || '',
        d: sub(this.sumKey([402, 405]).d, this.sumKey([404]).d) || '',
      }
      this.$set(this.editData[0], 'c', sum401.c)
      this.$set(this.editData[0], 'd', sum401.d)
      const sum406 = this.sumKey([407, 408, 409])
      this.$set(this.editData[5], 'c', sum406.c)
      this.$set(this.editData[5], 'd', sum406.d)
      const sum410 = {
        c: sub(this.sumKey([401]).c, this.sumKey([406]).c) || '',
        d: sub(this.sumKey([401]).d, this.sumKey([406]).d) || '',
      }
      this.$set(this.editData[9], 'c', sum410.c)
      this.$set(this.editData[9], 'd', sum410.d)
      const sum413 = {
        c: sub(this.sumKey([410, 411]).c, this.sumKey([412]).c) || '',
        d: sub(this.sumKey([410, 411]).d, this.sumKey([412]).d) || '',
      }
      this.$set(this.editData[12], 'c', sum413.c)
      this.$set(this.editData[12], 'd', sum413.d)
      const sum415 = {
        c: sub(this.sumKey([413]).c, this.sumKey([414]).c) || '',
        d: sub(this.sumKey([413]).d, this.sumKey([414]).d) || '',
      }
      this.$set(this.editData[14], 'c', sum415.c)
      this.$set(this.editData[14], 'd', sum415.d)
    },
    sumKey(arr) {
      let sum1 = 0
      let sum2 = 0
      arr.forEach(order => {
        const addItem = this.editData.find(item => +item.b === order) || {}
        sum1 += +addItem.c || 0
        sum2 += +addItem.d || 0
      })
      return {
        c: sum1 || '',
        d: sum2 || '',
      }
    },
    save() {
      const masterData = {
        year_type: 3,
        report_no: 'G4表',
        report_name: this.tableTitle,
        res_person: this.user.realName,
        phone_number: this.user.phoneNumber,
        year_number: this.queryYear,
        service_id: this.clientId,
        submit_person_name: this.user.realName,
        service_name: this.orgName,
      }
      if (this.tableInfo.report_year_id) {
        masterData.report_year_id = this.tableInfo.report_year_id
      }
      const slaveData = this.editData.map(item => {
        const data = {
          com_funds: item.c || 0,
          un_com_funds: item.d || 0,
          total_funds: add(item.c, item.d),
          order_num: item.b,
          dimension_key: item.b,
          dimension_key_name: item.a,
        }
        if (this.tableInfo.report_year_id) {
          data.report_year_id = this.tableInfo.report_year_id
          data.id = item.id
        }
        return data
      })
      const formData = {
        masterTableInfo: JSON.stringify(masterData),
        masterTableName: this.tableName,
        slaveTableInfo: JSON.stringify(slaveData),
        slaveTableName: 'report_year_income_detail',
      }
      this.saveLoading = true
      if (this.tableInfo.report_year_id) {
        this.$api
          .relatedUpdate(this.$serviceName, formData)
          .then(() => {
            this.$message.success('保存成功')
            this.$emit('success', true)
            this.getData()
            this.beforeClose()
          })
          .catch(() => {
            this.$message.error('保存失败，请重试！！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      } else {
        this.$api
          .relatedBatch(this.$serviceName, formData)
          .then(() => {
            this.$message.success('保存成功')
            this.$emit('success', true)
            this.getData()
            this.beforeClose()
          })
          .catch(() => {
            this.$message.error('保存失败，请重试！！')
          })
          .finally(() => {
            this.saveLoading = false
          })
      }
    },
    beforeClose() {
      this.editData = this.tableData.map(item => {
        return { ...item }
      })
      this.$emit('close', false)
    },
    handlePrint() {
      printWithIframe(document.getElementById(this.printId))
    },
    handleExport() {
      const borderAllThin = {
        left: { style: 'thin' },
        top: { style: 'thin' },
        right: { style: 'thin' },
        bottom: { style: 'thin' },
      }
      const borderAllNone = {
        left: { style: 'none' },
        top: { style: 'none' },
        right: { style: 'none' },
        bottom: { style: 'none' },
      }

      this.downloadLoading = true
      excelTableExport(this.printId, this.tableTitle, {
        styles: {
          border: borderAllNone,
          alignment: {
            vertical: 'center',
            horizontal: 'center',
            wrapText: true,
          },
        },
        cellStyles: {
          A1: {
            font: {
              sz: 24,
              name: '方正小标宋简体',
            },
          },
          A34: {
            alignment: {
              vertical: 'top',
              wrapText: true,
            },
          },
          A7: {
            border: borderAllThin,
          },
        },
        cols: [
          { wch: 40.63 },
          { wch: 4.0 },
          { wch: 34.5 },
          { wch: 24.0 },
          { wch: 24.0 },
          { wch: 34.5 },
        ],
        rows: {
          0: { hpx: 48 },
          33: { hpx: 180 },
        },
        cellHandler({ value, tr, td }) {
          const style = {}

          if (domHasClass(tr, 'bd-1')) {
            style.border = borderAllThin
          } else if (domHasClass(tr, 'bd-0')) {
            style.border = borderAllNone
          }

          if (domHasClass(td, 'text-right')) {
            style.alignment = { horizontal: 'bottom' }
          } else if (domHasClass(td, 'text-left')) {
            style.alignment = { horizontal: 'top' }
          }

          const { className = '' } = td
          const indent = /text-indent-(\d+)/.exec(className)
          if (indent) {
            value = `${' '.repeat(+(indent[1] || 0) * 8)}${value}`
          }

          return { value, style }
        },
      }).finally(() => {
        this.downloadLoading = false
      })
    },
  },
}
</script>

<style lang="scss" scoped>
$indents: 1, 2, 3;
@each $i in $indents {
  .text-indent-#{$i} {
    text-indent: $i * 2rem;
  }
}

.report-desc {
  font-size: 1rem;
  white-space: pre-wrap;
  font-family: 'Microsoft Yahei', '\5FAE\8F6F\96C5\9ED1', Helvetica, Arial, sans-serif;
}
</style>
